package chagine.mdt.utils;


import chagine.core.ErrorCode;
import chagine.core.exception.SeeingException;

import java.util.Calendar;
import java.util.Date;

/**
 * 年龄计算工具
 *
 * @author lyd on 2017/6/28.
 */
public class AgeUtils {


    /**
     * 通过出生日期计算年龄
     *
     * @param dateOfBirth
     * @return
     */
    public static String getAge(Date dateOfBirth) throws SeeingException {
        if (dateOfBirth == null) {
            return null;
        }
        int age = 0;
        int month = 0;
        int day = 0;
        Calendar born = Calendar.getInstance();
        Calendar now = Calendar.getInstance();
        now.setTime(new Date());
        born.setTime(dateOfBirth);
        if (born.after(now)) {
            throw new SeeingException(ErrorCode.BUSINESS_EXCEPTION, "出生年月不能超过当前日期");
        }
        age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);
        int nowDayOfYear = now.get(Calendar.DAY_OF_YEAR);
        int bornDayOfYear = born.get(Calendar.DAY_OF_YEAR);
//            System.out.println("nowDayOfYear:" + nowDayOfYear + " bornDayOfYear:" + bornDayOfYear);
        if (nowDayOfYear < bornDayOfYear - 1) {
            age -= 1;
        }
        month = now.get(Calendar.MONTH) - born.get(Calendar.MONTH);
        day = now.get(Calendar.DAY_OF_MONTH) - born.get(Calendar.DAY_OF_MONTH);
        if (day < 0) {
            day = day + 30;
            if (month <= 0) {
                month = month + 11;
            }
        } else {
            if (month < 0) {
                month = month + 12;
            }
        }
        String outAge;
        if (age >= 3) {
            outAge = age + "岁";
        } else if (age < 3 && age >= 1) {
            //一周岁到三周岁
            if (month == 0) {
                outAge = age + "岁";
            } else {
                outAge = age + "岁" + month + "月";
            }
        } else {
            //小于一周岁
            if (month == 0) {
                outAge = day + "天";
            } else {
                outAge = month + "月" + day + "天";
            }
        }
        return outAge;
    }
}
